import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class BacktrackSolution {

    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        LinkedList<Integer> track = new LinkedList<>();
        boolean[] used = new boolean[nums.length];
        backtrack(nums, track, used, result);
        return result;
    }

    private void backtrack(int[] nums, LinkedList<Integer> track, boolean[] used, List<List<Integer>> result) {
        if (track.size() == nums.length) {
            result.add(new LinkedList<>(track));
            return;
        }

        for (int i = 0; i < nums.length; i++) {
            if (used[i]) {
                continue;
            }
            used[i] = true;
            track.add(nums[i]);
            backtrack(nums, track, used, result);
            track.removeLast();
            used[i] = false;
        }
    }


    public List<List<String>> solveNQueens(int n) {
        List<List<String>> res = new ArrayList<>();
        List<String> board = new ArrayList<>(n);
        for (int i = 0; i < n; ++i) {
            StringBuilder builder = new StringBuilder(n);
            for (int j = 0; j < n; ++j) {
                builder.append('.');
            }
            board.add(builder.toString());
        }
        backtrack(board, 0, res);
        return res;
    }

    private void backtrack(List<String> board, int row, List<List<String>> res) {
        if (row == board.size()) {
            res.add(new ArrayList<>(board));
            return;
        }
        int n = board.size();
        for (int col = 0; col < n; ++col) {
            if (!isValid(board, row, col)) {
                continue;
            }
            StringBuilder builder = new StringBuilder(board.get(row));
            builder.setCharAt(col, 'Q');
            board.set(row, builder.toString());
            backtrack(board, row + 1, res);
            builder.setCharAt(col, '.');
            board.set(row, builder.toString());
        }
    }

    private boolean isValid(List<String> board, int row, int col) {
        int n = board.size();
        for (int i = 0; i < row; ++i) {
            if (board.get(i).charAt(col) == 'Q') {
                return false;
            }
        }

        for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; --i, --j) {
            if (board.get(i).charAt(j) == 'Q') {
                return false;
            }
        }

        for (int i = row - 1, j = col + 1; i >= 0 && j < n; --i, ++j) {
            if (board.get(i).charAt(j) == 'Q') {
                return false;
            }
        }
        return true;
    }


    public int totalNQueens(int n) {
        int[] count = {0};
        List<String> board = new ArrayList<>(n);
        for (int i = 0; i < n; ++i) {
            StringBuilder builder = new StringBuilder(n);
            for (int j = 0; j < n; ++j) {
                builder.append('.');
            }
            board.add(builder.toString());
        }
        backtrack(board, 0, count);
        return count[0];
    }

    private void backtrack(List<String> board, int row, int[] count) {
        if (row == board.size()) {
            ++count[0];
            return;
        }
        int n = board.size();
        for (int col = 0; col < n; ++col) {
            if (!isValid(board, row, col)) {
                continue;
            }
            StringBuilder builder = new StringBuilder(board.get(row));
            builder.setCharAt(col, 'Q');
            board.set(row, builder.toString());
            backtrack(board, row + 1, count);
            builder.setCharAt(col, '.');
            board.set(row, builder.toString());
        }
    }

    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        LinkedList<Integer> track = new LinkedList<>();
        backtrackSubsets(nums, res, track, 0);
        return res;
    }

    private void backtrackSubsets(int[] nums, List<List<Integer>> res, LinkedList<Integer> track, int startIndex) {
        res.add(new ArrayList<>(track));
        for (int i = startIndex; i < nums.length; ++i) {
            track.addLast(nums[i]);
            backtrackSubsets(nums, res, track, i + 1);
            track.removeLast();
        }
    }

    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> res = new ArrayList<>();
        LinkedList<Integer> track = new LinkedList<>();
        backtrackCombine(n, k, res, track, 0);
        return res;
    }

    private void backtrackCombine(int n, int k, List<List<Integer>> res, LinkedList<Integer> track, int startIndex) {
        if (track.size() == k) {
            res.add(new ArrayList<>(track));
        }
        for (int i = startIndex; i < n; ++i) {
            track.addLast(i + 1);
            backtrackCombine(n, k, res, track, i + 1);
            track.removeLast();
        }
    }

    public List<List<Integer>> subsetsWithDup(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> res = new ArrayList<>();
        LinkedList<Integer> track = new LinkedList<>();
        backtrackSubsetsWithDup(nums, res, track, 0);
        return res;
    }

    private void backtrackSubsetsWithDup(int[] nums, List<List<Integer>> res, LinkedList<Integer> track, int startIndex) {
        res.add(new ArrayList<>(track));
        for (int i = startIndex; i < nums.length; ++i) {
            if (i > startIndex && nums[i] == nums[i - 1]) {
                continue;
            }
            track.addLast(nums[i]);
            backtrackSubsets(nums, res, track, i + 1);
            track.removeLast();
        }
    }

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        List<List<Integer>> res = new ArrayList<>();
        LinkedList<Integer> track = new LinkedList<>();
        backtrackCombinationSum2(candidates, res, track, 0, target, 0);
        return res;
    }

    private void backtrackCombinationSum2(int[] candidates, List<List<Integer>> res, LinkedList<Integer> track, int startIndex, int target, int trackSum) {
        if (trackSum == target) {
            res.add(new ArrayList<>(track));
            return;
        }
        if (trackSum > target) {
            return;
        }

        for (int i = startIndex; i < candidates.length; ++i) {
            if (i > startIndex && candidates[i] == candidates[i - 1]) {
                continue;
            }
            track.addLast(candidates[i]);
            backtrackCombinationSum2(candidates, res, track, i + 1, target, trackSum + candidates[i]);
            track.removeLast();
        }
    }

    public List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        LinkedList<Integer> track = new LinkedList<>();
        Arrays.sort(nums);
        boolean[] used = new boolean[nums.length];
        backtrackPermuteUnique(nums, track, used, result);
        return result;
    }

    private void backtrackPermuteUnique(int[] nums, LinkedList<Integer> track, boolean[] used, List<List<Integer>> result) {
        if (track.size() == nums.length) {
            result.add(new LinkedList<>(track));
            return;
        }

        for (int i = 0; i < nums.length; i++) {
            if (used[i] || i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) {
                continue;
            }
            used[i] = true;
            track.add(nums[i]);
            backtrackPermuteUnique(nums, track, used, result);
            track.removeLast();
            used[i] = false;
        }
    }

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>();
        LinkedList<Integer> track = new LinkedList<>();
        backtrackCombinationSum(candidates, res, track, 0, target, 0);
        return res;
    }

    private void backtrackCombinationSum(int[] candidates, List<List<Integer>> res, LinkedList<Integer> track, int startIndex, int target, int trackSum) {
        if (trackSum == target) {
            res.add(new ArrayList<>(track));
            return;
        }
        if (trackSum > target) {
            return;
        }

        for (int i = startIndex; i < candidates.length; ++i) {
            track.addLast(candidates[i]);
            backtrackCombinationSum(candidates, res, track, i, target, trackSum + candidates[i]);
            track.removeLast();
        }
    }
}
